/**
 * 
 */
package sopia.sg;

import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Currency;
import java.util.Date;


import sopia.cmm.CommonFunct;
import sopia.cmm.Constant;
import sopia.conn.AccountAdapter;
import sopia.conn.CustomerSpinnerAdapter;
import sopia.conn.DBAdapter;
import sopia.conn.ItemExpenseAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.graphics.Typeface;
import android.opengl.Visibility;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.StyleSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author tatsu@gmail.com
 *
 */
public class G001Activity extends Activity {
	private AccountAdapter accAdapter ;
	private ItemExpenseAdapter itemAdapter;
	Spinner typeAccSpinner ;
	public static String valueAccountSelected;
	private String firstDayOfWeek;
	private String endDayOfWeek;
	private String today ; 
	//unit
	private TextView total_amount_main;
	private TextView unit_total_main;
	private TextView unit_spent_main;
	private TextView unit_today_main;
	private TextView unit_remain_main;
	private TextView unit_thisweek_main;
	//amount
	private TextView spent_amount_main;
	private TextView remain_amount_main;
	private TextView today_amount_main;
	private TextView week_amount_main;
	
	private TextView more_detail_view;
	private Calendar cal ;
	
	private static ArrayAdapter<CustomerSpinnerAdapter> adapter;
	public static double curAmountAccount;
	public static String curUnitCurrency;
	public static String curNameAccount;
	public static boolean flagExistAccount = true;
	/**
	 * 
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.g001_layout);
		init();		
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
	  //Handle the back button
	  if (keyCode == KeyEvent.KEYCODE_BACK) {
	    //Ask the user if they want to quit
	    new AlertDialog.Builder(this)
	      .setIcon(android.R.drawable.ic_dialog_alert)
	      .setTitle("Exit")
	      .setMessage("Are you sure you want to leave this application?")
	      .setNegativeButton(android.R.string.cancel, null)
	      .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
	        @Override
	        public void onClick(DialogInterface dialog, int which){
	          // Exit the activity
	        	G001Activity.this.finish();
	        }
	      })
	      .show();

	    // Say that we've consumed the event
	    return true;
	  }

	  return super.onKeyDown(keyCode, event);
	} 
	private void init() {

		unit_total_main = (TextView) findViewById(R.id.unit_total_main);
		unit_spent_main = (TextView) findViewById(R.id.unit_spent_main);
		unit_today_main = (TextView) findViewById(R.id.unit_today_main);
		unit_remain_main = (TextView) findViewById(R.id.unit_remain_main);
		unit_thisweek_main = (TextView) findViewById(R.id.unit_thisweek_main);
		//amount
		spent_amount_main = (TextView) findViewById(R.id.spent_amount_main);
		remain_amount_main = (TextView) findViewById(R.id.remain_amount_main);
		today_amount_main = (TextView) findViewById(R.id.today_amount_main);
		week_amount_main = (TextView) findViewById(R.id.week_amount_main);
		//
		more_detail_view = (TextView) findViewById(R.id.list_itemexpense_view);
        SpannableString ss = new SpannableString(
        "Click here to view more details.");

//        ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(),
//               Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new InternalURLSpan(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(G001Activity.this, G008Activity.class);
				i.putExtra("ID", "G001");
				startActivity(i);
				finish();
			}
		}), 6, 10,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
		more_detail_view.setText(ss);
		more_detail_view.setMovementMethod(LinkMovementMethod.getInstance());
		
		//
		TextView main = (TextView) findViewById(R.id.main);
		   cal = Calendar.getInstance();
		   cal.setFirstDayOfWeek(Calendar.MONDAY);
		   int year = cal.get(Calendar.YEAR);
		   int month = cal.get(Calendar.MONTH);
		   int day = cal.get(Calendar.DAY_OF_MONTH);
		   
		   today =String.valueOf(year) + "/" + String.valueOf(month + 1) + "/" + String.valueOf(day);
		   String mybudget = getString(R.string.mybudget);
		   main.setText(mybudget +  " - Today " + today);
		   
		   int daysSinceMonday = (7 + cal.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY)% 7;	  
		  // Date date = new Date(year, month + 1, day);
		   cal.add(Calendar.DATE, -(daysSinceMonday - 1));
		   //Date firstDay = cl.get
		   int yearFirst = cal.get(Calendar.YEAR);
		   int monthFirst = cal.get(Calendar.MONTH);
		   int dayFirst = cal.get(Calendar.DAY_OF_MONTH);
		   this.firstDayOfWeek = String.valueOf(yearFirst) + "/" + String.valueOf(monthFirst  + 1) + "/" + String.valueOf(dayFirst);
		

		   cal.add(Calendar.DATE, 6 );
		   int yearEnd = cal.get(Calendar.YEAR);
		   int monthEnd = cal.get(Calendar.MONTH);
		   int dayEnd = cal.get(Calendar.DAY_OF_MONTH);
		   this.endDayOfWeek = String.valueOf(yearEnd) + "/" + String.valueOf(monthEnd  + 1 ) + "/" + String.valueOf(dayEnd);
		//init spinner
		   initAccountSpinner();
		   
		   
		//
		final ImageButton forwardSettingImageButton = (ImageButton) findViewById(R.id.forward_setting_imageButton);
		forwardSettingImageButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent i = new Intent(G001Activity.this, G002Activity.class);
				i.putExtra("ID", "G001");
				startActivity(i);
				finish();
			}
		});
		// imageButton_view
		final ImageButton imageButton_view = (ImageButton) findViewById(R.id.imageButton_view);
		imageButton_view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(G001Activity.this, G006Activity.class);
				i.putExtra("ID", "G001");
				startActivity(i);
			}
		});
		//typeAccSpinner
		total_amount_main = (TextView) findViewById(R.id.total_amount_main);
		typeAccSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				CustomerSpinnerAdapter account = (CustomerSpinnerAdapter) typeAccSpinner.getItemAtPosition(position);
				valueAccountSelected = account.getValue();
				curNameAccount = valueAccountSelected;
				//search Account
				showAllItem();
			}

			public void onNothingSelected(AdapterView<?> parent) {
//				if(typeAccSpinner.getCount() > 0 ) {
//					   CustomerSpinnerAdapter account = (CustomerSpinnerAdapter) typeAccSpinner.getItemAtPosition(0);
//					   curNameAccount = account.getValue();
//				   }
			}
		});
		setOldValueScreen();
	}
	static class InternalURLSpan extends ClickableSpan {  
	    OnClickListener mListener;  
	  
	    public InternalURLSpan(OnClickListener listener) {  
	        mListener = listener;  
	    }  
	  
	    @Override  
	    public void onClick(View widget) {  
	        mListener.onClick(widget);  
	    }  
	}  
	private void setOldValueScreen() {
		int spinnerPosition1 = CommonFunct.getIndexFromElement(adapter, curNameAccount);
		//set the old according to value
		typeAccSpinner.setSelection(spinnerPosition1);		
	}

	protected void showAllItem() {
		try {
			//search Account
			accAdapter = new AccountAdapter(this);	
			itemAdapter = new ItemExpenseAdapter(this);
			String amountAcc = accAdapter.getAmountCurrency(valueAccountSelected);
			
			String[] amountCurrency = CommonFunct.removeHash(amountAcc);
			DecimalFormat formatter = new DecimalFormat("#,###");
			
			String total = formatter.format(Double.parseDouble(amountCurrency[0]));
			total_amount_main.setText(total);
			curAmountAccount = Double.parseDouble(amountCurrency[0]);
			setUnitCurrentMain(amountCurrency[1]);
			//amount 
			String spent_amount = itemAdapter.getAmountSpent();
			spent_amount_main.setText(spent_amount);
			String remain_amount = this.getAmountRemain(amountCurrency[0],spent_amount);
			remain_amount_main.setText(remain_amount);
			
			String today_amount = itemAdapter.getAmountByWeek(this.today, this.today);
			today_amount_main.setText(today_amount);
			String week_amount = itemAdapter.getAmountByWeek(this.firstDayOfWeek,this.endDayOfWeek);
			week_amount_main.setText(week_amount);
			
			accAdapter.close();
			itemAdapter.close();
		} catch (NumberFormatException e) {
			Log.d(e.toString(), "G001-showAllItem-NumberFormatException");
		} catch (SQLException e) {
			Log.d(e.toString(), "G001-showAllItem-SQLException");
		}
	}

	private String getAmountRemain(String total, String spent_amount) {
		double remain = 0 ;
		try {
			double dTotal = Double.parseDouble(total);
			double dSpent = Double.parseDouble(spent_amount);
			if(dSpent == 0){
				more_detail_view.setVisibility(8);
			}else{
				more_detail_view.setVisibility(0);
			}
			remain = dTotal - dSpent;
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return String.valueOf(remain);
	}

	private void setUnitCurrentMain(String str) {
		unit_total_main.setText(str);
		unit_spent_main.setText(str);
		unit_remain_main.setText(str);
		unit_today_main.setText(str);
		unit_thisweek_main.setText(str);
		curUnitCurrency = str;
		
	}

	private void initAccountSpinner() {
		try {
			typeAccSpinner = (Spinner) findViewById(R.id.typeAccount_main);
//			//get data
			accAdapter = new AccountAdapter(this);	
			Cursor cur = accAdapter.getAllAccount();
			if(cur.getCount() <= 0) {
				flagExistAccount = false;
				more_detail_view.setVisibility(8);
			}
			accAdapter.close();
//			//set data
			final CustomerSpinnerAdapter[] items = CommonFunct.getSpinnerAdapter(cur);
			adapter = new ArrayAdapter<CustomerSpinnerAdapter>(
					this, android.R.layout.simple_spinner_item, items);
			adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			typeAccSpinner.setAdapter(adapter);
			if (cur != null && !cur.isClosed()) {
		      cur.close();
		    }
		} catch (Exception e) {
			Log.e("G001-initAccountSpinner", e.toString());
		}
	}
	
	

}
